/**
 * http配置
 */
import axios from "axios";
import vm from "@/main";
import store from "@/store";
import { APIENV } from "@/utils/constant";
import { uuid4, md5 } from "@/utils";

const instance = axios.create(); // 生成一个axios实例
// 超时时间15s
instance.defaults.timeout = 15000;
// 全局的 axios 默认值
instance.defaults.baseURL = APIENV[process.env.VUE_APP_APIENV] || APIENV.prod;

instance.defaults.headers.post["Content-Type"] =
  "application/json;charset=UTF-8";

instance.defaults.headers.common["x"] = "x";
// http请求拦截器
instance.interceptors.request.use(
  config => {
    vm.$indicator.open({ text: "加载中..." });
    let wx = JSON.parse(window.localStorage.getItem("wx"))
    if ("post" === config.method) {
      const openid = store.getters["user/openid"] || wx.openid;
      const token = store.getters["user/token"] || wx.token;
      const Yhdtoken = store.getters["user/Yhdtoken"] || null;
      const userId = store.getters["user/userId"] || null;
      const version = process.env.VUE_APP_VERSION;
      const timeStamp = Date.parse(new Date());
      /* 将openid和yhdtoken,userId合并进请求参数中 */
      let params = { Yhdtoken, openid, userId, ...config.data };
      params = params ? JSON.stringify(params) : null;
      const nonse = uuid4() + uuid4() + uuid4() + uuid4(); // 16位随机码
      const signature = md5(
        `nonse=${nonse}&params=${params}&timeStamp=${timeStamp}&token=${token}`
      );
      // console.log("signature:", signature);
      const data = { nonse, params, timeStamp, token, signature, version };
      config.data = data;
    }
    return config;
  },
  error => {
    vm.$indicator.close();
    vm.$toast({ message: "加载超时", position: "bottom", duration: 2000 });
    return Promise.reject(error);
  }
);

// http响应拦截器

/* token失效code */
const expire_codes = ["000800"];

/* 退出重新登录 */
const logout = msg => {
  vm.$store.dispatch("logout");
  vm.$messagebox.alert(msg).then(() => {
    vm.$router.replace({
      name: "login",
      query: { redirect: vm.$router.currentRoute.fullPath }
    });
  });
};

instance.interceptors.response.use(
  data => {
    vm.$indicator.close();
    // token过期
    if (expire_codes.includes(data.data.respCode)) {
      logout(data.data.respMsg);
      return {};
    }
    return data.data;
  },
  error => {
    vm.$indicator.close();
    console.log("error: ", JSON.stringify(error));
    console.log("response：", error.response);

    if (typeof error.response == "object") {
      let data = error.response.data;
      if (data && expire_codes.includes(data.respCode)) {
        // token过期
        logout(data.respMsg);
      } else {
        // 其他错误
        vm.$messagebox.alert(data.respMsg);
      }
      return Promise.reject(error);
    }
    let message = /timeout/gi.test(error) ? "请求超时" : "网络错误";
    vm.$toast({
      message: message,
      position: "bottom",
      duration: 2000
    });
    return Promise.reject(error);
  }
);

export default instance;
